package cn.micai.base.asyn;

import java.util.concurrent.*;

/**
 * 描述：通过Future实现
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/11 13:42
 */
public class FutureDemo2 {

    public static void main(String [] args) throws ExecutionException, InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<String> future = executorService.submit(new RealData());

        System.out.println("RealData方法调用完毕");
        // 模拟主函数中其他耗时操作
        doOtherThing();
        // 获取RealData2方法的结果
        System.out.println(future.get());

    }

    private static void doOtherThing() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class RealData implements Callable<String> {

        public String costTime() {
            try {
                // 模拟RealData耗时操作
                Thread.sleep(1000);
                return "result";
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "exception";
        }

        @Override
        public String call() throws Exception {
            return costTime();
        }
    }
}
